<template>
  <div class="service-container">
    <el-card class="table-card">
      <template #header>
        <div class="table-header">
          <h3>送水服务管理</h3>
          <div class="search-toggle-area">
            <el-button class="search-toggle-button" @click="toggleSearchBar">
              <el-icon><Search /></el-icon>
            </el-button>
            <el-form :inline="true" :model="queryParams" class="search-form" :class="{'is-hidden': !showSearchBar}" ref="queryForm">
              <el-form-item label="状态">
                <el-select v-model="queryParams.status" placeholder="请选择状态" clearable style="width: 160px;">
                  <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="联系电话">
                <el-input v-model="queryParams.contact_phone" placeholder="请输入联系电话" clearable></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="handleQuery">查询</el-button>
                <el-button @click="resetQuery">重置</el-button>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </template>

      <el-table 
        v-loading="loading" 
        :data="waterDeliveryList" 
        border 
        stripe 
        :header-cell-style="{background:'#f5f7fa', color:'#606266'}"
      >
        <el-table-column prop="id" label="服务单号" width="100" align="center" />
        <el-table-column label="申请人" width="120" align="center">
           <template #default="{ row }">
            {{ row.applicant_user_info?.name || 'N/A' }}
          </template>
        </el-table-column>
        <el-table-column prop="contact_phone" label="联系电话" width="140" align="center" />
        <el-table-column prop="delivery_address" label="配送地址" min-width="250" align="center" />
        <el-table-column prop="product_name" label="商品" width="150" align="center" />
        <el-table-column prop="quantity" label="数量" width="80" align="center" />
        <el-table-column prop="application_time" label="申请时间" width="180" align="center">
          <template #default="{ row }">
            {{ new Date(row.application_time).toLocaleString() }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="140" align="center">
            <template #default="{ row }">
                <el-tag :type="getStatusType(row.status)" size="small">{{ row.status }}</el-tag>
            </template>
        </el-table-column>
        <el-table-column label="配送员" width="120" align="center">
           <template #default="{ row }">
            {{ row.deliverer_user_info?.name || '---' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="120" align="center" class-name="small-padding fixed-width">
          <template #default="{ row }">
            <el-button
              v-if="row.status === '待受理'"
              type="primary"
              link
              @click="openAssignDialog(row)"
            >
              指派
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-empty v-if="waterDeliveryList.length === 0 && !loading" description="暂无送水服务数据" class="empty-data-placeholder"></el-empty>
      
      <div class="pagination-container">
        <el-pagination 
          v-show="total > 0" 
          :total="total" 
          :current-page="queryParams.current" 
          :page-size="queryParams.size" 
          @size-change="handleSizeChange" 
          @current-change="handleCurrentChange"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
        ></el-pagination>
      </div>
    </el-card>

    <!-- 指派配送员对话框 -->
    <el-dialog v-model="dialogVisible" title="指派配送员" width="500px" append-to-body>
      <el-form>
        <el-form-item label="选择配送员">
          <el-select v-model="selectedDeliverer" placeholder="请选择配送员">
            <el-option
              v-for="staff in deliveryStaff"
              :key="staff.user_id"
              :label="staff.name"
              :value="staff.user_id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleAssign">确认指派</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { getWaterDeliveryList, assignWaterDeliverer } from '@/api/services';
import { getDeliveryStaffList } from '@/api/users';
import { ElMessage } from 'element-plus';
import { Search } from '@element-plus/icons-vue';

const waterDeliveryList = ref([]);
const loading = ref(true);
const dialogVisible = ref(false);
const deliveryStaff = ref([]);
const selectedDeliverer = ref(null);
const currentServiceId = ref(null);
const total = ref(0);
const showSearchBar = ref(false);

// 查询参数
const queryParams = reactive({
  current: 1,
  size: 10,
  status: '',
  contact_phone: ''
});

// 状态选项
const statusOptions = ref([
  { value: '待受理', label: '待受理' },
  { value: '配送中', label: '配送中' },
  { value: '已送达', label: '已送达' },
  { value: '已评价', label: '已评价' },
  { value: '已取消', label: '已取消' }
]);

// 获取送水服务列表
const fetchWaterDeliveries = async () => {
  loading.value = true;
  try {
    const response = await getWaterDeliveryList(queryParams);
    // 适配新的返回格式
    if (response.data && response.data.code === 200) {
      waterDeliveryList.value = response.data.data.list;
      total.value = response.data.data.total || waterDeliveryList.value.length;
    } else {
      waterDeliveryList.value = [];
      total.value = 0;
    }
  } catch (error) {
    ElMessage.error('获取送水服务列表失败');
    console.error(error);
    waterDeliveryList.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
};

const fetchDeliveryStaff = async () => {
  try {
    const response = await getDeliveryStaffList();
    if (response.data && response.data.code === 200) {
      deliveryStaff.value = response.data.data.list;
    } else {
      deliveryStaff.value = [];
      ElMessage.error(response.data.message || '获取配送员列表失败');
    }
  } catch (error) {
    ElMessage.error('获取配送员列表失败');
    console.error(error);
    deliveryStaff.value = [];
  }
};

const getStatusType = (status) => {
    switch (status) {
        case '待受理': return 'warning';
        case '配送中': return 'primary';
        case '已送达': return 'success';
        case '已评价': return 'success';
        case '已取消': return 'info';
        default: return 'info';
    }
};

// 切换搜索栏显示状态
const toggleSearchBar = () => {
  showSearchBar.value = !showSearchBar.value;
};

// 搜索和重置
const handleQuery = () => {
  queryParams.current = 1;
  fetchWaterDeliveries();
};

const resetQuery = () => {
  queryParams.status = '';
  queryParams.contact_phone = '';
  handleQuery();
};

// 分页：每页数量变化
const handleSizeChange = (size) => {
  queryParams.size = size;
  fetchWaterDeliveries();
};

// 分页：当前页变化
const handleCurrentChange = (current) => {
  queryParams.current = current;
  fetchWaterDeliveries();
};

// 打开指派对话框
const openAssignDialog = (service) => {
  currentServiceId.value = service.id;
  selectedDeliverer.value = null;
  dialogVisible.value = true;
};

// 处理指派逻辑
const handleAssign = async () => {
  if (!selectedDeliverer.value) {
    ElMessage.warning('请选择一位配送员');
    return;
  }
  try {
    await assignWaterDeliverer(currentServiceId.value, selectedDeliverer.value);
    ElMessage.success('指派成功');
    dialogVisible.value = false;
    fetchWaterDeliveries(); // 重新加载数据
  } catch (error) {
    ElMessage.error('指派失败');
    console.error(error);
  }
};

onMounted(() => {
  fetchWaterDeliveries();
  fetchDeliveryStaff(); // 获取配送员列表
});
</script>

<style scoped>
.service-container {
  padding: 20px;
  background-color: #f8f9fa;
  min-height: calc(100vh - 80px);
}

.table-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.05);
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.table-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

/* 搜索区域 */
.search-toggle-area {
  display: flex;
  flex-direction: row;
  align-items: center;
}

.search-toggle-button {
  font-size: 20px;
  color: #606266;
  align-self: center;
  margin-right: 15px;
  transition: all 0.2s;
  cursor: pointer;
  width: 36px;
  height: 36px;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 50%;
  background-color: rgba(0, 0, 0, 0.03);
  border: 1px solid rgba(0, 0, 0, 0.05);
  z-index: 10;
  margin-bottom: 0;
}

.search-toggle-button:hover {
  color: #409eff;
  background-color: rgba(64, 158, 255, 0.1);
  border-color: rgba(64, 158, 255, 0.2);
}

.search-form {
  max-width: 1000px;
  width: auto;
  overflow: hidden;
  transition: max-width 0.4s ease-in-out, opacity 0.4s ease-in-out, background-color 0.4s ease-in-out, box-shadow 0.4s ease-in-out, padding 0.4s ease-in-out, margin-left 0.4s ease-in-out, height 0.4s ease-in-out, min-height 0.4s ease-in-out;
  opacity: 1;
  background-color: transparent;
  border-radius: 8px;
  padding: 0 20px;
  box-shadow: none;
  pointer-events: auto;
  margin-left: 15px;
  white-space: nowrap;
  height: 35px;
  min-height: 35px;
}

.search-form.is-hidden {
  max-width: 0;
  opacity: 0;
  padding: 0;
  margin-left: 0;
  height: 0;
  min-height: 0;
  background-color: transparent;
  box-shadow: none;
  pointer-events: none;
}

/* 调整搜索表单项的底部外边距 */
:deep(.search-form .el-form-item) {
  margin-bottom: 0;
  margin-right: 15px;
  display: inline-flex;
  align-items: center;
}

:deep(.search-form .el-form-item__label) {
  padding-right: 8px;
}

:deep(.table-card .el-card__header) {
  background-color: #f9fafc;
  padding: 15px 20px;
}

:deep(.table-card .el-card__body) {
  padding: 20px;
}

.pagination-container {
  margin-top: 25px;
  display: flex;
  justify-content: flex-end;
  padding: 12px 15px;
  background-color: #f9fbfd;
  border-radius: 10px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.03);
}

.empty-data-placeholder {
  margin-top: 40px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 搜索框el-input优化 */
:deep(.el-input__inner) {
  border-color: #e0e5ed !important;
  transition: border-color 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
  border-radius: 6px;
}

:deep(.el-input__inner:focus) {
  border-color: rgba(64, 158, 255, 0.4) !important;
}

:deep(.el-input__inner::placeholder) {
  color: #aebccf;
}

/* 按钮el-button优化 */
:deep(.el-button--primary) {
  background-color: rgba(64, 158, 255, 0.1) !important;
  color: #606266 !important;
  border-color: rgba(64, 158, 255, 0.2) !important;
  transition: all 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
  border-radius: 6px;
}

:deep(.el-button--primary:hover) {
  background-color: rgba(64, 158, 255, 0.15) !important;
  border-color: rgba(64, 158, 255, 0.3) !important;
}

/* Default Button */
:deep(.el-button--default) {
  background-color: #ffffff !important;
  color: #606266 !important;
  border-color: #dcdfe6 !important;
  transition: all 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
  border-radius: 6px;
}

:deep(.el-button--default:hover) {
  background-color: #f7f9fa !important;
  border-color: #c8d3dd !important;
}

/* Danger Button */
:deep(.el-button--danger) {
  background-color: rgba(245, 108, 108, 0.1) !important;
  color: #F56C6C !important;
  border-color: rgba(245, 108, 108, 0.2) !important;
  transition: all 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
  border-radius: 6px;
}

:deep(.el-button--danger:hover) {
  background-color: rgba(245, 108, 108, 0.15) !important;
  border-color: rgba(245, 108, 108, 0.3) !important;
}
</style> 